package com.gu.myviewmodel.services

import com.gu.myviewmodel.app.log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
class NetworkService @Inject constructor() {
    //https://gitee.com/developergu/my-view-model/raw/master/jsondata/data.json
    private val retrofit = Retrofit.Builder().baseUrl("https://gitee.com/developergu/my-view-model/raw/master/")
        .client(OkHttpClient()).addConverterFactory(GsonConverterFactory.create()).build()

    private val carService = retrofit.create(CarDataService::class.java)

    suspend fun allCars(): List<Car> {
        val cars = withContext(Dispatchers.IO) {
            carService.getCars().also {
                log("获取了${it.size}条数据!")
            }
        }
        cars.forEach {
            log("car: $it")
        }
        return cars
    }

    private fun log(str: String) {
        log("NetworkService", str)
    }
}

interface CarDataService {
    @GET("jsondata/data.json")
    suspend fun getCars(): List<Car>
}

